import { memo, useRef, useEffect } from 'react'
import * as echarts from 'echarts'

interface IProps {
	option: echarts.EChartsCoreOption
	width?: string
	height?: string
}

const Echarts = memo((props: IProps) => {
	const { option, width = '100%', height = '100%' } = props

	const myChart = useRef<echarts.EChartsType>()
	const echartsRef = useRef<HTMLDivElement>(null)

	const echartsResize = () => {
		echartsRef && myChart?.current?.resize()
	}

	useEffect(() => {
		if (echartsRef?.current) {
			myChart.current = echarts.init(echartsRef?.current)
		}
		myChart?.current?.setOption(option)
		window.addEventListener('resize', echartsResize, false)
		return () => {
			window.removeEventListener('resize', echartsResize)
			myChart?.current?.dispose()
		}
	}, [])

	useEffect(() => {
		if (myChart?.current) {
			myChart?.current?.setOption(option)
		}
	}, [option])

	return <div ref={echartsRef} style={{ width, height }}></div>
})

export default Echarts
